import math
import os
from  tqdm import tqdm
import numpy
from PIL import Image
import numpy as np
file_dir = '/home/xys/paper/ReID/data_vehicle_test/bounding_box_test_wei/'
save_dir = '/home/xys/paper/ReID/data_vehicle_test/bounding_box_test/'
file_name = os.listdir(file_dir)
for file in tqdm(file_name):
    img = Image.open(file_dir+file).convert('RGB')
    #img.show()
    img_array = np.array(img)#把图像转成数组格式img = np.asarray(image)
    shape = img_array.shape
    print(img_array.shape)
    nums = []
    for i in range(0,shape[0]):
        num = 0
        for j in range(0,shape[1]):
            value = img_array[i, j]
            #print("",value)
            if value[0] > 160 and value[0]< 180:
                num+=1
                # print("", value)
        nums.append(num)
    nums = numpy.array(nums)
    first_h = nums.argmax()
    second_h = first_h
    while(math.fabs(first_h-second_h)<99):
        nums[second_h] = 0
        second_h = nums.argmax()
    temp = 0
    if first_h < second_h:
        temp = first_h
        first_h = second_h
        second_h = temp

    nums = []
    for j in range(0,shape[1]):
        num = 0
        for i in range(0,shape[0]):
            value = img_array[i, j]
            #print("",value)
            if value[0] > 160 and value[0]< 180:
                num+=1
                # print("", value)
        nums.append(num)
    nums = numpy.array(nums)
    first_w = nums.argmax()
    second_w = first_w
    while(math.fabs(first_w-second_w)<99):
        nums[second_w] = 0
        second_w = nums.argmax()
    temp = 0
    if first_w < second_w:
        temp = first_w
        first_w = second_w
        second_w = temp
    _width, _height = img.size
    Vehicle = img.crop((second_w, second_h, first_w, first_h)) # 需要的范围(left, upper, right, lower)
    Vehicle.save(save_dir+file)




